package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.OrderDao;
import com.itheima.dao.OrderSettingDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Member;
import com.itheima.pojo.Order;
import com.itheima.pojo.OrderSetting;
import com.itheima.service.MemberService;
import com.itheima.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/*
类简介：

功能：

时间：2020/4/6

*/
@Service(interfaceClass = OrderService.class)
public class OrderServiceImpl implements OrderService{

    @Autowired
    OrderDao orderDao;

    @Autowired
    OrderSettingDao orderSettingDao;

    @Autowired
    MemberService memberService;

    //判断预约是否已满
    @Override
    public int isFull(Date orderDate) {
        return orderSettingDao.ifFull(orderDate);
    }

    @Override
    public Map<String,Object> findById(int id) {
        return orderDao.findById(id);
    }

    @Override
    public PageResult findPage(QueryPageBean queryPageBean, Map<String, Object> pagination) {

        List<Object> date = (List<Object>) pagination.get("date");
        String orderType = pagination.get("orderType") == null? null:pagination.get("orderType").toString();
        String visitedStatus = pagination.get("visitedStatus") ==null ? null: pagination.get("visitedStatus").toString();
        String queryString = pagination.get("queryString") == null?"%%":"%" + pagination.get("queryString").toString().trim() + "%";

        PageHelper.startPage(queryPageBean.getCurrentPage()<0?1:queryPageBean.getCurrentPage(),queryPageBean.getPageSize());
        Page<Map<String,String>> orders;
        if (date != null){

            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

            String  date1 =date.get(0).toString().substring(0,10);
            String  date2 =date.get(1).toString().substring(0,10);

            orders = orderDao.findPageWithDate(date1,date2,orderType,visitedStatus,queryString);
            return new PageResult(orders.getTotal(),orders.getResult());
        }else {
            orders = orderDao.findPageWithoutDate(orderType,visitedStatus,queryString);
            return new PageResult(orders.getTotal(),orders.getResult());
        }
    }

    @Override
    public void add(Map<String,Object> order, Integer[] setmealIds) {

        if (order.get("orderDate") == null){
            throw new RuntimeException("日期必填");
        }

        //获取冰存储member信息
        Member member = new Member();
        if (order.get("phoneNumber") != null){
            member.setPhoneNumber(order.get("phoneNumber").toString());
        }
        if(order.get("memberName") != null){
            member.setName(order.get("memberName").toString());
        }

        Integer memberId = memberService.addMember(member);

        //填充数据
        Order order1 = new Order();
        order1.setMemberId(memberId);

        //格式化日期部分
        String format = order.get("orderDate").toString();
        System.out.println("format = " + format);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date orderDate;
        try {
            orderDate = simpleDateFormat.parse(format);
            order1.setOrderDate(orderDate);
        } catch (ParseException e) {
            throw new RuntimeException("日期格式解析错误");
        }

        //放入其他数据
        order1.setOrderStatus(Order.ORDERSTATUS_NO);
        order1.setOrderType(Order.ORDERTYPE_TELEPHONE);

        for (Integer setmealId : setmealIds) {
            order1.setSetmealId(setmealId);
            addOrder(order1);
        }
    }

    @Override
    public Map<String, Object> findByIdForEdit(int id) {
        Map<String, Object> map = orderDao.findByIdForEdit(id);
        List<Integer> ids = orderDao.findSetmealByOrderId(id,map.get("member_id"),map.get("orderDate"));
        map.put("setmealIds",ids);
        return map;
    }

    @Override
    public void edit(Order order, Integer[] setmealIds) {
        orderDao.deleteById(order.getId());
        for (Integer setmealId : setmealIds) {
            order.setSetmealId(setmealId);
            try {
                orderDao.addOrder(order);
            }catch (Exception e){
                throw new RuntimeException("已存在相同的预约，现已将本次修改的预约删除");
            }
        }
    }

    @Override
    public void deleteById(int id) {
        int delete = orderDao.deleteById(id);
        if(delete == 0){
            throw new RuntimeException("数据库异常请联系管理员");
        }
    }

    @Override
    public void editVisitedStatus(int id,String status) {
        int edit = orderDao.editVisitedStatus(id,status);
        if(edit == 0){
            throw new RuntimeException("数据库异常请联系管理员");
        }
    }

    @Override
    public int addOrder(Order order) {

        //判断是否重复
        if (orderDao.isExit(order) > 0){
            throw new RuntimeException("不可重复预约");
        }

        if (orderDao.addOrder(order) == 0){
            throw new RuntimeException("插入数据库失败");
        }

        //成功后在预约日历上加一
        OrderSetting orderSetting = new OrderSetting();
        orderSetting.setOrderDate(order.getOrderDate());
        orderSettingDao.addOneOrder(orderSetting);

        return order.getId();
    }
}
